from abc import ABC

from tornado.web import RequestHandler


class BaseHandler(RequestHandler, ABC):

    # 浏览器安全验证
    def set_default_headers(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Max-Age', 1000)
        self.set_header('Content-type', '*')
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, DELETE, PUT, PATCH, OPTIONS')
        self.set_header('Access-Control-Allow-Headers',
                        'Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers, '
                        'X-Requested-By, Access-Control-Allow-Methods, JSESSION')

    def options(self, *args, **kwargs):
        pass

    async def write_error_log(self, id_, reason, param=""):
        async with self.application.mysql.acquire() as conn:
            async with conn.cursor() as cur:
                try:
                    await cur.execute(
                        f"""
INSERT INTO alibb.`alibb_container_log` (
  member_id,
  error_reason,
  error_param
) VALUE ("{id_}", "{reason}", "{param}")
        """)
                except Exception as e:
                    await conn.rollback()
                    raise e

    async def insert(self, sql_, reason, param=""):

        async with self.application.mysql.acquire() as conn:

            async with conn.cursor() as cur:
                try:
                    await cur.execute(sql_)
                except Exception as e:
                    await conn.rollback()
                    await self.write_error_log(self.current_user['member_id'], reason, param)
                    raise e
